<template>
  <div class="es-demo-block">
    <!-- 代码演示 -->
    <div class="es-demo-block-area" v-if="demoComponent">
      <component :is="demoComponent"></component>
    </div>

    <!-- 操作区域 -->
    <div class="es-demo-block-footer">
      <es-tooltip tooltip="展示代码">
        <div :class="['es-icon-item', { active: showCode }]" @click="showCode = !showCode">
          <Code style="color:#ccc "></Code>
        </div>
      </es-tooltip>
      <es-tooltip tooltip="复制代码">
        <div class="es-icon-item" @click="copyClipboard(decodeURIComponent(props.codeString))">
          <Copy style="color:#ccc "></Copy>
        </div>
      </es-tooltip>
    </div>

    <!-- 源码 -->
    <div :class="['es-demo-block-source', { 'es-source-open': showCode }]">
      <div class="es-demo-block-source-inner">
        <pre class="language-html" v-html="htmlCode"></pre>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="es-demo-block">
import { Code, Copy } from "earthsdk-icon";
import { Message } from "earthsdk-ui";
import { computed, defineAsyncComponent, markRaw, onMounted, ref } from "vue";
import './style.css'
import hljs from 'highlight.js'
import 'highlight.js/styles/color-brewer.css'

interface Prop {
  src: string;
  codeString?: string;
  lang?: string;
}
const props = withDefaults(defineProps<Prop>(), {
  src: "",
  codeString: "",
  lang: "html",
});

const exampleGlob = import.meta.glob(`../../../src/example/**/*.vue`);
/** 示例文件组件 */
const demoComponent = ref();
/** 是否展示源码 */
const showCode = ref<boolean>(false);

const htmlCode = computed(() => {
  const code = hljs.highlight(decodeURIComponent(props.codeString), { language: props.lang }).value
  return code
})

onMounted(() => {
  demoComponent.value = markRaw(defineAsyncComponent(exampleGlob[`../../../src/${props.src}.vue`] as any));
});

const copyClipboard = (text: string) => {//复制
  navigator.clipboard.writeText(text)
    .then(function () {
      Message.success('复制成功');
    }, function () {
      Message.error('复制失败');
    });
}
</script>

<style scoped>
:deep(.min-light) {
  background: none !important;
}
</style>
